package com.njbw;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * 长沙先飞信息科技有限公司<br>
 * Created with IntelliJ IDEA.<br>
 * Date:2025/9/2<br>
 * Time:14:19<br>
 * 功能描述：<br>
 *
 * @author huang hou chun
 * @since JDK 1.8 <br>
 * Copyright (c) 2023 www.csxfrj.com System Incorporated All Rights Reserved.
 */
public class Handler extends Thread {

    Socket socket;

    public Handler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try (InputStream is = this.socket.getInputStream()) {
            try (OutputStream os = this.socket.getOutputStream()) {
                handle(is, os);
            }
        } catch (Exception ignored) {
        } finally {
            try {
                this.socket.close();
            } catch (IOException ignored) {}
            System.out.println("client disconnected");
        }
    }

    private void handle(InputStream is, OutputStream os) throws IOException {
        System.out.println("Process new HTTP request...");
        // 用 reader 读取 HTTP 请求
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        // 用 Writer 发送 HTTP 响应
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8));
        // 读取 HTTP 请求
        boolean requestOk = false;
        String first = reader.readLine();
        if (first.startsWith("GET / HTTP/1.")) {
            requestOk = true;
        }
        for (;;) {
            String header = reader.readLine();
            if (header.isEmpty()) {
                // 读取到空行，HTTP Header 读取完毕
                break;
            }
            System.out.println(header);
        }
        System.out.println(requestOk ? "Response OK" : "Response Error");
        if (requestOk) {
            // 发送成功响应:
            String data = "<html><body><h1>Hello, world!</h1></body></html>";
            int length = data.getBytes(StandardCharsets.UTF_8).length;
            writer.write("HTTP/1.0 200 OK\r\n");
            writer.write("Connection: close\r\n");
            writer.write("Content-Type: text/html\r\n");
            writer.write("Content-Length: " + length + "\r\n");
            writer.write("\r\n"); // 空行标识Header和Body的分隔
            writer.write(data);
            writer.flush();
        } else {
            // 发送错误响应:
            writer.write("HTTP/1.0 404 Not Found\r\n");
            writer.write("Content-Length: 0\r\n");
            writer.write("\r\n");
            writer.flush();
        }
    }
}
